package logic

import (
	"context"
	"github.com/zeromicro/go-zero/core/logx"
	"goods-guru/goodrpc/goodrpc"
	"goods-guru/goodrpc/internal/svc"
	"goods-guru/models/mysql"
)

type GoodAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGoodAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GoodAddLogic {
	return &GoodAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GoodAddLogic) GoodAdd(in *goodrpc.GoodAddRequest) (*goodrpc.GoodAddResponse, error) {
	// todo: add your logic here and delete this line
	var class mysql.Class
	begin := mysql.DB.Debug().Begin()
	mysql.DB.Debug().Where("name=?", in.ClassName)
	if class.ID == 0 {
		class = mysql.Class{
			Name: in.ClassName,
		}
		err := begin.Debug().Create(&class).Error
		if err != nil {
			begin.Rollback()
			return nil, err
		}
	}
	var brand mysql.Brand
	mysql.DB.Debug().Where("name=?", in.BrandName)
	if brand.ID == 0 {
		brand = mysql.Brand{
			Name: in.BrandName,
		}
		err := begin.Debug().Create(&brand).Error
		if err != nil {
			begin.Rollback()
			return nil, err
		}
	}
	good := mysql.Good{
		Title:   in.Title,
		ClassId: int(class.ID),
		BrandId: int(brand.ID),
	}
	err := begin.Debug().Create(&good).Error
	if err != nil {
		begin.Rollback()
		return nil, err
	}
	return &goodrpc.GoodAddResponse{
		GoodId: int64(good.ID),
	}, nil
}
